<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RoleRealm - 用户设置</title>
    <link rel="stylesheet" href="/css/style.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'PingFang SC', 'Inter', sans-serif; background: #f8fafc; min-height: 100vh; }
        .header { background: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 15px 0; }
        .header-content { max-width: 1200px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; padding: 0 20px; }
        .logo { color: #1e3a8a; font-size: 24px; font-weight: bold; cursor: pointer; }
        .header-actions { display: flex; gap: 15px; }
        .header-btn { padding: 8px 16px; border: none; border-radius: 20px; background: #f8fafc; color: #1e3a8a; cursor: pointer; font-size: 14px; transition: all 0.3s ease; }
        .header-btn.primary { background: #f59e0b; color: white; }
        .main-container { max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 250px 1fr; gap: 20px; padding: 20px; }
        .settings-nav { background: #1e3a8a; border-radius: 15px; padding: 20px; height: fit-content; }
        .nav-title { color: white; font-size: 18px; font-weight: bold; margin-bottom: 20px; }
        .nav-item { display: block; padding: 12px 16px; color: #e5e7eb; text-decoration: none; border-radius: 10px; margin-bottom: 8px; transition: all 0.3s ease; cursor: pointer; }
        .nav-item:hover { background: rgba(255, 255, 255, 0.1); color: white; }
        .nav-item.active { background: #f59e0b; color: white; }
        .settings-content { background: white; border-radius: 15px; padding: 30px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); }
        .content-title { font-size: 24px; font-weight: bold; color: #1e3a8a; margin-bottom: 20px; }
        .user-info { display: flex; align-items: center; gap: 20px; margin-bottom: 30px; padding: 20px; background: #f8fafc; border-radius: 15px; }
        .user-avatar { width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 32px; font-weight: bold; }
        .form-group { margin-bottom: 20px; }
        .form-label { display: block; font-size: 14px; font-weight: bold; color: #374151; margin-bottom: 8px; }
        .form-input, .form-select { width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 10px; font-size: 14px; transition: all 0.3s ease; }
        .slider { width: 100%; }
        .history-list { max-height: 400px; overflow-y: auto; }
        .history-item { display: flex; align-items: center; gap: 15px; padding: 15px; border: 1px solid #e5e7eb; border-radius: 10px; margin-bottom: 10px; transition: all 0.3s ease; }
        .history-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px; font-weight: bold; }
        .favorites-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }
        .favorite-item { display: flex; align-items: center; gap: 12px; padding: 15px; border: 1px solid #e5e7eb; border-radius: 10px; transition: all 0.3s ease; }
        .favorite-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px; font-weight: bold; }
        .favorite-remove { padding: 4px 8px; border: none; border-radius: 4px; background: #ef4444; color: white; font-size: 12px; cursor: pointer; }
        @media (max-width: 768px) { .main-container { grid-template-columns: 1fr; padding: 10px; } .settings-nav { order: 2; } .user-info { flex-direction: column; text-align: center; } }
    </style>
    <script src="/js/api.js"></script>
    <script src="/js/auth.js"></script>
</head>
<body>
    <header class="header">
        <div class="header-content">
            <div class="logo" onclick="location.href='/character-selection.html'">RoleRealm</div>
            <div class="header-actions">
                <button class="header-btn" onclick="location.href='/character-selection.html'">返回首页</button>
                <button class="header-btn primary" onclick="Auth.logout()">退出登录</button>
            </div>
        </div>
    </header>

    <div class="main-container">
        <nav class="settings-nav">
            <h3 class="nav-title">设置</h3>
            <a class="nav-item active" data-section="profile">个人资料</a>
            <a class="nav-item" data-section="voice">语音偏好</a>
            <a class="nav-item" data-section="history">对话历史</a>
            <a class="nav-item" data-section="favorites">收藏角色</a>
        </nav>

        <main class="settings-content">
            <div id="profile-section" class="settings-section">
                <h2 class="content-title">个人资料</h2>
                <div class="user-info">
                    <div class="user-avatar" id="userAvatar">用</div>
                    <div class="user-details">
                        <h3 id="userName">用户名</h3>
                        <p id="userEmail">user@example.com</p>
                    </div>
                </div>
                <div class="form-group"><label class="form-label" for="nickname">昵称</label><input type="text" id="nickname" class="form-input" placeholder="请输入昵称"></div>
                <div class="form-group"><label class="form-label" for="avatarUrl">头像 URL</label><input type="text" id="avatarUrl" class="form-input" placeholder="https://..."></div>
                <button class="header-btn primary" id="saveProfileBtn">保存资料</button>
            </div>

            <div id="voice-section" class="settings-section" style="display:none">
                <h2 class="content-title">语音偏好</h2>
                <div class="form-group"><label class="form-label" for="voiceSpeed">语速</label><input type="range" id="voiceSpeed" min="0.5" max="2" step="0.1" class="slider"></div>
                <div class="form-group"><label class="form-label" for="voicePitch">音调</label><input type="range" id="voicePitch" min="0.5" max="2" step="0.1" class="slider"></div>
                <div class="form-group"><label class="form-label" for="voiceVolume">音量</label><input type="range" id="voiceVolume" min="0" max="100" step="1" class="slider"></div>
                <div class="form-group"><label class="form-label" for="preferredVoice">默认语言</label>
                    <select id="preferredVoice" class="form-select">
                        <option value="zh-CN">中文</option>
                        <option value="en-US">英文</option>
                        <option value="auto">自动检测</option>
                    </select>
                </div>
                <button class="header-btn primary" id="savePrefBtn">保存偏好</button>
            </div>

            <div id="history-section" class="settings-section" style="display:none">
                <h2 class="content-title">对话历史</h2>
                <div id="historyList" class="history-list"></div>
            </div>

            <div id="favorites-section" class="settings-section" style="display:none">
                <h2 class="content-title">收藏角色</h2>
                <div id="favoritesGrid" class="favorites-grid"></div>
            </div>
        </main>
    </div>

    <script>
      Auth.requireAuth();
      // Navigation
      document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', () => {
          document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
          document.querySelectorAll('.settings-section').forEach(s => s.style.display = 'none');
          item.classList.add('active');
          document.getElementById(item.dataset.section + '-section').style.display = 'block';
        });
      });

      async function loadMe() {
        const me = await UsersApi.me();
        document.getElementById('userName').textContent = me.username || me.nickname || '用户';
        document.getElementById('userEmail').textContent = me.email || '';
        document.getElementById('nickname').value = me.nickname || '';
        document.getElementById('avatarUrl').value = me.avatarUrl || '';
        document.getElementById('userAvatar').textContent = (me.nickname || me.username || '用').slice(0,1);
      }

      async function saveProfile() {
        const payload = { nickname: document.getElementById('nickname').value.trim(), avatarUrl: document.getElementById('avatarUrl').value.trim() };
        await UsersApi.updateMe(payload);
        await loadMe();
        alert('资料已保存');
      }

      async function loadPreferences() {
        try {
          const p = await PreferencesApi.get();
          document.getElementById('voiceSpeed').value = p.voiceSpeed ?? 1;
          document.getElementById('voicePitch').value = p.voicePitch ?? 1;
          document.getElementById('voiceVolume').value = p.voiceVolume ?? 80;
          document.getElementById('preferredVoice').value = p.preferredVoice || 'auto';
        } catch (_) {}
      }

      async function savePreferences() {
        const payload = {
          voiceSpeed: Number(document.getElementById('voiceSpeed').value),
          voicePitch: Number(document.getElementById('voicePitch').value),
          voiceVolume: Number(document.getElementById('voiceVolume').value),
          preferredVoice: document.getElementById('preferredVoice').value
        };
        await PreferencesApi.update(payload);
        alert('偏好已保存');
      }

      async function loadHistory() {
        const wrap = document.querySelector('#history-section #historyList');
        wrap.innerHTML = '';
        const data = await ConversationsApi.list(1, 50);
        const list = data.list || [];
        list.forEach(h => {
          const item = document.createElement('div');
          item.className = 'history-item';
          const ch = (h.title || '会话').slice(0,1);
          const time = h.lastMessageAt ? new Date(h.lastMessageAt).toLocaleString() : '';
          item.innerHTML = `<div class="history-avatar">${ch}</div><div class="history-info"><div class="history-character">${h.title || '会话'}</div><div class="history-time">${time}</div></div><div class="history-actions"><button class="header-btn" data-act="open">继续</button><button class="header-btn" data-act="del">删除</button></div>`;
          item.querySelector('[data-act="open"]').addEventListener('click', () => {
            location.href = `/chat.html?conversationId=${h.id || h.conversationId}`;
          });
          item.querySelector('[data-act="del"]').addEventListener('click', async () => {
            if (confirm('确定删除此会话？')) { await ConversationsApi.delete(h.id || h.conversationId); item.remove(); }
          });
          wrap.appendChild(item);
        });
      }

      async function loadFavorites() {
        const grid = document.getElementById('favoritesGrid');
        grid.innerHTML = '';
        const data = await UsersApi.favorites(1, 100);
        const list = data.list || [];
        list.forEach(c => {
          const item = document.createElement('div');
          item.className = 'favorite-item';
          item.innerHTML = `<div class="favorite-avatar">${(c.name || '角')[0]}</div><div class="favorite-info"><div class="favorite-name">${c.name}</div><div class="favorite-category">${c.category || ''}</div></div><button class="favorite-remove">移除</button>`;
          item.querySelector('.favorite-remove').addEventListener('click', async () => { await UsersApi.removeFavorite(c.id); item.remove(); });
          grid.appendChild(item);
        });
      }

      document.getElementById('saveProfileBtn').addEventListener('click', () => { saveProfile().catch(e => alert(e.message || '保存失败')); });
      document.getElementById('savePrefBtn').addEventListener('click', () => { savePreferences().catch(e => alert(e.message || '保存失败')); });

      (async function init(){
        try {
          await Promise.all([loadMe(), loadPreferences(), loadHistory(), loadFavorites()]);
        } catch (e) { console.error(e); }
      })();
    </script>
</body>
</html>


